<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<table id="racers" border="1" cellspacing="0" style="width:100%">
    <th>Id</th>
    <th>Name</th>
</table>
<script>
//根据名称name打开数据库
var db = openDatabase('db', '1.0', 'my first database', 2 * 1024 * 1024);

function log(id, name) {
	var row = document.createElement("tr");
	var idCell = document.createElement("td");
	var nameCell = document.createElement("td");
	idCell.textContent = id;
	nameCell.textContent = name;
	row.appendChild(idCell);
	row.appendChild(nameCell);

	document.getElementById("racers").appendChild(row);
}

function doQuery() {
	db.transaction(function (tx) {
		tx.executeSql('SELECT * from mytable', [], function(tx, result) {
			//显示查询的记录集
			for (var i=0; i<result.rows.length; i++) {
				var item = result.rows.item(i);
				log(item.id, item.name);
			}
		});
	});
}

function initDatabase() {
	var names = ["张三", "李四", "王五", "赵六", "侯七", "abc", "def"];
	db.transaction(function (tx) {
		tx.executeSql('CREATE TABLE IF NOT EXISTS mytable(id integer primary key autoincrement, name)');

		for (var i=0; i<names.length; i++) {
			tx.executeSql('INSERT INTO mytable (name) VALUES (?)', [names[i]]);
		}

		doQuery();
	});
}
initDatabase();
</script>
</body>
</html>  

